//
//  SearchDevicesVC.m
//  DLNA_Demo
//


#import "SearchDevicesVC.h"
#import "MRDLNA.h"
#import "ChooseLaunchTypeVC.h"
#import "LocalPicturesVC.h"
#import "LocalVideosVC.h"
#import "LocalShowPicVC.h"
#import "LocalShowVideoVC.h"
#import <Photos/Photos.h>
#import <Masonry/Masonry.h>
#import "Reachability.h"
#import "WIFIHelper.h"
#import <CoreLocation/CoreLocation.h>
#import "ConstAndMacros.h"
#import <MJRefresh/MJRefresh.h>
@interface SearchDevicesVC ()<UITableViewDelegate,UITableViewDataSource,DLNADelegate,CLLocationManagerDelegate>
@property (nonatomic,strong)UIActivityIndicatorView *activityView;
@property (nonatomic,strong)UITableView  *baseV;
@property (nonatomic,strong)NSArray  *devicesArr;
@property (nonatomic,strong)MRDLNA  *dlnaManager;
@property (weak, nonatomic) IBOutlet UILabel *labelTitle;
@property (weak, nonatomic) IBOutlet UILabel *labelWifi;
@property (nonatomic,strong) CLLocationManager *locManager;
@property (weak, nonatomic) IBOutlet UIView *viewHeader;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewHeaderHeight;
@end

@implementation SearchDevicesVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"搜索设备";
    [self setUpUI];
    [self makeActivityView];
//    [self makeRightBtn];
    [self makeDlnaManager];
    [self refresh];
    [self getLocation];
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse ||
        status == kCLAuthorizationStatusAuthorizedAlways) {
        //再重新获取ssid
        //初始化Reachability类，并添加一个监测的网址。
        Reachability *hostReach = [Reachability reachabilityForInternetConnection];
        //开始监测
        NSInteger st = [hostReach currentReachabilityStatus];
        
        if (st == kReachableViaWiFi) {
            NSString *ssid = [WIFIHelper ssid];
            self.labelWifi.text = [NSString stringWithFormat:@"已连接到网络 %@",ssid];
        }else {
            self.labelWifi.text = @"请连接WIFI";
        }
    }
    
}

- (void)getLocation
{
    if (!self.locManager) {
        self.locManager = [[CLLocationManager alloc] init];
        
    }
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //这句代码会在app的设置中开启位置授权的选项，只有用户选择了允许一次，下次用户调用这个方法才会弹出询问框，选择不允许或是使用期间允许，下次调用这个方法都不会弹出询问框
        [self.locManager requestAlwaysAuthorization];
        
    }
    
    self.locManager.delegate = self;
    //如果用户第一次拒绝了，弹出提示框，跳到设置界面，要用户打开位置权限
    //如果用户跳到设置界面选择了下次询问，再回到app,[CLLocationManager authorizationStatus]的值会是nil,所以要||后面的判断
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied || ![CLLocationManager authorizationStatus]) {
        [self alertMy];
    }
}

- (void)alertMy{
       //1.创建UIAlertControler
       UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"app需要获取您的位置权限，以获取wifi信息" preferredStyle:UIAlertControllerStyleAlert];
     
       UIAlertAction *conform = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           //使用下面接口可以打开当前应用的设置页面
//           [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
           NSLog(@"点击了确认按钮");
       }];
       //2.2 取消按钮
       UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
           NSLog(@"点击了取消按钮");
       }];
    
       //3.将动作按钮 添加到控制器中
       [alert addAction:conform];
       [alert addAction:cancel];
       
       //4.显示弹框
       [self presentViewController:alert animated:YES completion:nil];
}
-(void)makeDlnaManager{
    self.dlnaManager = [MRDLNA sharedMRDLNAManager];
    self.dlnaManager.delegate  = self;
}

-(NSArray*)devicesArr{
    if(_devicesArr==nil){
        _devicesArr = [NSArray  array];
    }
    return _devicesArr;
}

-(void)setUpUI{
    self.baseV = [UITableView new];
//    self.baseV.frame = self.view.bounds;
    [self.view addSubview:self.baseV];
    self.baseV.delegate = self;
    self.baseV.dataSource = self;
    self.baseV.tableFooterView = [UIView new];
    [self.baseV mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(@0);
        make.top.mas_equalTo(@(200));
    }];
    self.baseV.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.labelTitle.text = @"";

}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.devicesArr.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchDevicesVC"];
    if(!cell){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SearchDevicesVC"];
    }
    CLUPnPDevice *device = self.devicesArr[indexPath.row];
    cell.textLabel.text = device.friendlyName;
    cell.imageView.image = [UIImage imageNamed:@"icon_device"];
    return  cell;
}

- (void)addDefaultView {
    UIView *oldView = [self.baseV viewWithTag:1000];
    if (oldView) {
        [oldView removeFromSuperview];
    }
    UIView *maskView = [UIView new];
    maskView.tag = 1000;
    [self.baseV addSubview:maskView];
    [maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(@(kScreenWidth));
        make.height.mas_equalTo(@(kScreenHeight - kNavigationBarHeight - 200));
        make.center.mas_equalTo(0);
//        make.top.mas_equalTo(0);
//        make.left.right.bottom.mas_equalTo(0);
    }];
//    maskView.backgroundColor = [UIColor orangeColor];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"device_img_placeholder"]];
    [maskView addSubview:imageView];
    [imageView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(@0);
    }];
    UILabel *labelTitle = [UILabel new];
    labelTitle.text = @"暂未发现设备，下拉刷新";
    labelTitle.font = [UIFont systemFontOfSize:13];
    [maskView addSubview:labelTitle];
    [labelTitle mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(@0);
        make.top.mas_equalTo(imageView.mas_bottom).offset(20);
    }];

    UILabel *labelDes = [UILabel new];
    labelDes.text = @"（请确保手机与电视处于同一 WIFI 下）";
    labelDes.font = [UIFont systemFontOfSize:13];
    labelDes.textColor = [UIColor dj_colorWithHex:@"#717D84"];
    [maskView addSubview:labelDes];
    [labelDes mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(labelTitle.mas_bottom).offset(20);
    }];
    
}
- (void)removeDefaultView {
    UIImageView *view = [self.baseV viewWithTag:1000];
    [view removeFromSuperview];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.dlnaManager.device =  self.devicesArr[indexPath.row];
    if (self.delegate && [self.delegate respondsToSelector:@selector(didConnectDevice:)]) {
        [self.delegate didConnectDevice:self.dlnaManager.device];
    }
    [self.navigationController popViewControllerAnimated:YES];
    
//    if(self.playType == 0){
//        LocalShowPicVC *picShow = [LocalShowPicVC new];
//        picShow.assetsArr = self.assets;
//        picShow.currentIndex = 0;
//        [self.navigationController pushViewController:picShow animated:YES];
//    }else if (self.playType == 1){
//        dispatch_async(dispatch_get_global_queue(0, 0), ^{
//            NSArray *allFiles = [self getAllMoviesForLocalShow];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                if (self.delegate && [self.delegate respondsToSelector:@selector(searchDevicesDidBackWithAssets:)]) {
//                    [self.delegate searchDevicesDidBackWithAssets:allFiles];
//                }
//                [self.navigationController popViewControllerAnimated:YES];
//            });
//        });
//    }
}
- (NSArray *)getAllMoviesForLocalShow {
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    NSMutableArray* files = [NSMutableArray new];
//    [self.assets enumerateObjectsUsingBlock:^(PHAsset * assert, NSUInteger idx, BOOL * _Nonnull stop) {
//        [[PHImageManager defaultManager] requestAVAssetForVideo:assert options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
//            if (asset) {
//                AVURLAsset *urlAsset = (AVURLAsset *)asset;
//                NSURL *url = urlAsset.URL;
//                NSString *path = [url path];
//                NSDateFormatter* format = [NSDateFormatter new];
//                format.dateFormat = @"yyyy-MM-dd hh:mm aa";
//                [files addObject:@{@"url" : path?path:@"", @"title" : @"--",@"asset":asset}];
//            }
//            dispatch_semaphore_signal(semaphore);
//        }];
//        dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
//    }];
    return files;
}

-(void)makeRightBtn{
    UIButton *btn = [[UIButton alloc]init];
    btn.frame = CGRectMake(0, 0, 100, 60);
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [btn setTitle:@"重新搜索" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(refresh) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
}

-(void)makeActivityView{
    self.activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.activityView setColor:[UIColor lightGrayColor]];
    self.activityView.center = CGPointMake([UIScreen mainScreen].bounds.size.width / 2, 200);
}

-(void)refresh{
    self.devicesArr = nil;
    [self.baseV reloadData];
    [self.dlnaManager startSearch];
    [self.view addSubview:self.activityView];
    [self.activityView startAnimating];
}

-(void)searchDLNAResult:(NSArray *)devicesArray{
    self.devicesArr = devicesArray;
    [self.baseV.mj_header endRefreshing];
    if (self.devicesArr.count == 0) {
        [self addDefaultView];
    }else{
        [self removeDefaultView];
    }
    [self.baseV reloadData];
    [self.activityView removeFromSuperview];
}

-(void)dlnaDidEndSearch{
    NSLog(@"结束搜索");
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.devicesArr.count == 0) {
            self.labelTitle.text = @"未发现设备";
        }else {
            self.labelTitle.text = @"";
        }
    });
}

-(void)dealloc{
//    if (self.playType == 0) {
//        [MRDLNA destory];
//    }
    NSLog(@"%s",__FUNCTION__);
}

@end
